#!/usr/bin/python

import os.path
import math
import linecache
import sys

#------------------------------------------------------------------------------
#Global variables
experiment_name = sys.argv[2]
gmmOutputFolder = '/home/sergi/work/Alarms_detection/recognition/' + experiment_name + '/'
resultsFolder = '/home/sergi/work/Alarms_detection/metric_results/'
CORPUS = ['S3', 'S4', 'S11', 'S12', 'S13', 'S14', 'S15', 'S16', 'S17', 'S18']
#CORPUS = ['S3']
SCENARIOS = ['SC1', 'SC2', 'SC3', 'SC4', 'SC5', 'SC6', 'SC7', 'SC8', 'SC9', 'SC10']
#SCENARIOS = ['SC1']
EXTRAS = [ '', '_2' ]
#TIERS = [ 'alarms', 'vocalizations', 'noises' ]
TIERS = [ 'alarms' ]

#Indexes of labels
START_TIME = 0
END_TIME = 1
CLASS = 2

class_of_interest = "al"
evaluation_interval = sys.argv[1] #in seconds
evaluation_interval = int(evaluation_interval)

#------------------------------------------------------------------------------
# Separation part.
for session in CORPUS:
    path = gmmOutputFolder + session + '/' + 'out_merged_-10.mmf'
    if not os.path.isfile(path):
        continue
    else:
        inputFile = open(path, 'r')
        newpath = gmmOutputFolder + 'evaluation_interval_' + str(evaluation_interval) + '/' + session + '/'
        if not os.path.exists(newpath):
            os.makedirs(newpath)
        with open(path) as fileID:
            for line in fileID:
                if not line[0].isdigit():
                    if (line != '#!MLF!#\n' and line != '.\n'):
                        name = line.split('/')
                        name = name[8]
                        name = name.split('_')
                        if (len(name) == 3):
                            name = name[1] + '_' + name[2]
                        else:
                            name = name[1]
                        name = name.split('.')
                        name = name[0]
                        outputFile = open(newpath + session + '_' + name + '.txt', 'w')
                if (line == '.\n'):
                    outputFile.close()
                if (line[0].isdigit()):
                    interval = line.split(' ')
                    outputFile.write(str(float(interval[START_TIME])/10000000) + ',' + str(float(interval[END_TIME])/10000000) + ',' + str(interval[CLASS]) + '\n')
inputFile.close()
outputFile.close()

# Label creating part.
outputFile2 = open(gmmOutputFolder + 'evaluation_interval_' + str(evaluation_interval) + '/' + 'overall_last_interval.txt', 'w')
for session in CORPUS:
    for scenario in SCENARIOS:
        for extra in EXTRAS:
            path = gmmOutputFolder + 'evaluation_interval_' + str(evaluation_interval) + '/' + session + '/' + session + '_' + scenario + extra + '.txt'
            if not os.path.isfile(path):
                continue
            inputFile = open(path, 'r')
            outputFile = open(gmmOutputFolder + 'evaluation_interval_' + str(evaluation_interval) + '/' + session + '/' + session + '_' + scenario + extra + '.csv', 'w')
            with open(path) as fileID:
                interval_index = 1
                interval_counts = 0
                interval_partials = 0
                for line in fileID:
                    if not line[0].isdigit():
                        continue
                    interval = line.split(',')
                    interval_start = (interval_index - 1) * evaluation_interval
                    interval_end = interval_index * evaluation_interval
                    if class_of_interest in interval[CLASS]:
                        if (float(interval[START_TIME]) == float(interval_end)):
                            if (interval_counts > 1 or interval_counts >= 1 and interval_partials > 0):
                                outputFile.write(str(interval_start) + ',' + str(interval_end) + ',' + 'al' + '\n')
                            else:
                                outputFile.write(str(interval_start) + ',' + str(interval_end) + ',' + 'ot' + '\n')
                            interval_index += 1
                            interval_counts = 0
                            interval_partials = 0
                        if (float(interval[END_TIME]) > float(interval_end) and float(interval[START_TIME]) != float(interval_end)):
                            interval_partials += 1
                            if (interval_counts > 1 or interval_counts >= 1 and interval_partials > 0):
                                outputFile.write(str(interval_start) + ',' + str(interval_end) + ',' + 'al' + '\n')
                            else:
                                outputFile.write(str(interval_start) + ',' + str(interval_end) + ',' + 'ot' + '\n')
                            interval_index += 1
                            interval_counts = 0
                            interval_partials = 1
                        else:
                            interval_counts += 1
                    else:
                        previous_interval_index = interval_index
                        if (float(interval[END_TIME]) > float(interval_end)):
                            interval_index = int(math.ceil((float(interval[END_TIME]) - evaluation_interval)/evaluation_interval)+1)
                        if (float(interval[END_TIME]) >= float(interval_end) and interval_index - previous_interval_index >= 1):
                            for x in range (previous_interval_index, interval_index):
                                interval_start = (x - 1) * evaluation_interval
                                interval_end = x * evaluation_interval
                                if (interval_counts > 1 or interval_counts >= 1 and interval_partials > 0):
                                    outputFile.write(str(interval_start) + ',' + str(interval_end) + ',' + 'al' + '\n')
                                else:
                                    outputFile.write(str(interval_start) + ',' + str(interval_end) + ',' + 'ot' + '\n')
                                interval_counts = 0
                                interval_partials = 0
                if (float(interval[END_TIME]) - float(interval_start) - float(evaluation_interval) < 0): #calculate last interval
                    last_interval = str(float(interval[END_TIME]) - float(interval_start))
                else:
                    last_interval = str(float(interval[END_TIME]) - float(interval_start) - float(evaluation_interval))
                outputFile2.write(last_interval + '\n')
                interval_index = 1
                interval_counts = 0
                interval_partials = 0
inputFile.close()
outputFile.close()
outputFile2.close()
